import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useUserStore = defineStore('user', () => {
    //定义state
    const token = ref('')
    const id = ref('')
    const name = ref('')
    const avatar = ref('')
    const roles = ref([])
    const permissions = ref([])

    //定义action
    function Login(userInfo) {
        const username = userInfo.username.trim()
        const password = userInfo.password
        const captcha = userInfo.captcha
        const uuid = userInfo.uuid
        return new Promise((resolve, reject) => {
            login(username, password, captcha, uuid)
                .then((res) => {
                    setToken(res.data.token)
                    token.value = getToken()
                    resolve()
                })
                .catch((error) => {
                    reject(error)
                })
        })
    }

    function GetInfo() {
        return new Promise((resolve, reject) => {
            getInfo()
                .then((res) => {
                    if (res && res.data) {
                        const { user, roles: new_roles, permissions: new_permissions } = res.data
                        if (new_roles && new_roles.length > 0) {
                            roles.value = new_roles
                            permissions.value = new_permissions
                        } else {
                            roles.value = ['ROLE_DEFAULT']
                        }
                        id.value = user.id
                        name.value = user.name
                        avatar.value = user.avatar
                        resolve(res.data)
                    }
                })
                .catch((error) => {
                    reject(error)
                })
        })
    }
    function LogOut() {
        return new Promise((resolve, reject) => {
            logout(token.value)
                .then(() => {
                    token.value = ''
                    roles.value = []
                    permissions.value = []
                    removeToken()
                    resolve()
                })
                .catch((error) => {
                    reject(error)
                })
        })
    }
    return { token, id, name, avatar, roles, permissions, Login, GetInfo, LogOut }
})
